import request from '@/utils/request';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { message } from 'antd';
import { history } from 'umi';

// 定义登录响应数据类型
interface LoginResponseData {
  token: string;
  userId: string;
}

export default () => {
  const handleLogin = async (values: any) => {
    try {
      // 调用登录接口
      const response = await request<LoginResponseData>('/login/loginIn', {
        method: 'POST',
        data: {
          account: values.account,
          password: values.password,
        },
      });

      if (response.code === '0000') {
        // 登录成功，保存token和userId
        localStorage.setItem('token', response.data.token);
        localStorage.setItem('userId', response.data.userId);
        localStorage.setItem(
          'user',
          JSON.stringify({
            name: values.account,
            role: 'admin',
          }),
        );
        // 显示登录成功提示

        message.success('登录成功！');
        const urlParams = new URL(window.location.href).searchParams;
        history.push(urlParams.get('redirect') || '/');
      } else {
        message.error(response.msg || '登录失败，请重试');
      }
    } catch (error) {
      console.error('登录请求出错:', error);
      message.error('登录失败，请重试');
    }
  };

  return (
    <div
      style={{
        height: '100vh',
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <LoginForm
        title="管理系统"
        subTitle="欢迎登录"
        onFinish={handleLogin}
        style={{
          background: '#fff',
          padding: '40px',
          borderRadius: '8px',
          boxShadow: '0 4px 20px rgba(0, 0, 0, 0.1)',
          minWidth: '400px',
        }}
      >
        <ProFormText
          name="account"
          fieldProps={{
            size: 'large',
            prefix: <UserOutlined />,
          }}
          placeholder="请输入账号"
          rules={[
            {
              required: true,
              message: '请输入账号!',
            },
          ]}
        />
        <ProFormText.Password
          name="password"
          fieldProps={{
            size: 'large',
            prefix: <LockOutlined />,
          }}
          placeholder="密码: 123456"
          rules={[
            {
              required: true,
              message: '请输入密码!',
            },
          ]}
        />
      </LoginForm>
    </div>
  );
};
